﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using BLL;
using DAL;

namespace CTRL
{
    public sealed class CtrlMap
    {
        private static volatile CtrlMap instance;
        private static object syncRoot = new Object();
        private static Map map;

        private IDALEdge edgesRepository;

        public CtrlMap()
        {
            this.edgesRepository = new DALEdge(new CarBatteryEntities());
            map = new Map();

            UpdateMapStations();
        }

        public List<BatteryCenterDistance> GetPathFromCityToCity(BatteryCenter from, BatteryCenter to, double carRange)
        {
            PathFinder pathFinder = new PathFinder();

            return pathFinder.FindPathFromCityToCity(map, from, to, carRange);
        }

        private void UpdateMapStations()
        {
            CtrlBatteryStation ctrlBS = CtrlBatteryStation.Instance;

            IEnumerable<BatteryCenter> p = ctrlBS.GetAllStations().Select(b => new BatteryCenter { name = b.name, stationID = b.stationID, timeOpen = b.timeOpen, timeClose = b.timeClose, Mark = false });

            map.Stations = p.ToList();

            foreach (var n in map.Stations)
                n.Edgelist = edgesRepository.GetBatteryCenterEdges(n.name);
        }

        public IList<BatteryCenter> GetAllCities()
        {
            return map.Stations;
        }

        public BatteryCenter FindCity(string name)
        {
            return map.Stations.FirstOrDefault(x => x.name.Contains(name));
        }

        public static CtrlMap Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new CtrlMap();
                    }
                }

                return instance;
            }
        }
    }
}